<template>
  <view class="membership-container">
    <!-- 导航栏 -->
    <view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="back-button" @tap="goBack">
        <text class="iconfont icon-back">〈</text>
      </view>
      <view class="title">专享特权</view>
    </view>
    
    <!-- VIP会员信息卡片 -->
    <view class="vip-card">
      <view class="vip-header">
        <view class="vip-icon">V</view>
        <view class="vip-title">
          <text class="main-title">高级AI模型VIP</text>
          <text class="sub-title">开通高级AI模型会员，享真人一般的交流体验</text>
        </view>
        <view class="vip-badge">权益</view>
      </view>
      
      <!-- 会员套餐选择 -->
      <view class="plan-options">
        <view 
          class="plan-card" 
          :class="{ active: selectedPlan === 'monthly' }"
          @tap="selectPlan('monthly')"
        >
          <view class="plan-price">
            <text class="price-symbol">¥</text>
            <text class="price-value">9.90</text>
          </view>
          <view class="plan-details">
            <text class="plan-name">月卡</text>
            <text class="plan-duration">一月/30天；0.33/天</text>
          </view>
        </view>
        
        <view 
          class="plan-card" 
          :class="{ active: selectedPlan === 'yearly' }"
          @tap="selectPlan('yearly')"
        >
          <view class="plan-price">
            <text class="price-symbol">¥</text>
            <text class="price-value">99.00</text>
          </view>
          <view class="plan-details">
            <text class="plan-name">年卡</text>
            <text class="plan-duration">一年/365天；0.27/天</text>
          </view>
        </view>
      </view>
      
      <!-- 立即开通按钮 -->
      <view class="subscribe-btn-container">
        <button 
          class="subscribe-btn" 
          :loading="subscribing" 
          :disabled="subscribing"
          @tap="handleSubscribe"
        >立即开通</button>
      </view>
      
      <view class="terms-text">数字虚拟产品无退款服务</view>
    </view>
    
    <!-- VIP会员权益列表 -->
    <!-- VIP会员权益列表 -->
    <view class="benefits-section">
      <view class="section-title">会员权益</view>
      <view class="benefits-list">
        <view class="benefit-item">
          <text class="benefit-icon">✓</text>
          <text class="benefit-text">无限畅聊，无次数限制</text>
        </view>
        <view class="benefit-item">
          <text class="benefit-icon">✓</text>
          <text class="benefit-text">无限切换智能体，随心体验多种AI</text>
        </view>
        <view class="benefit-item">
          <text class="benefit-icon">✓</text>
          <text class="benefit-text">优先体验最新AI模型</text>
        </view>
        <view class="benefit-item">
          <text class="benefit-icon">✓</text>
          <text class="benefit-text">专属客服，优先响应</text>
        </view>
        <view class="benefit-item">
          <text class="benefit-icon">✓</text>
          <text class="benefit-text">更多会员专属功能持续解锁中…</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
// membership.vue 的 script 部分
import { ref, computed, onMounted } from 'vue'
import { useUserStore, useMembershipStore, useWechatStore } from '@/stores'
import { system, message } from '@/utils'
import { getBaseUrl } from '@/utils/address'

const userStore = useUserStore()
const membershipStore = useMembershipStore()
const wechatStore = useWechatStore() // 新增微信状态管理
const statusBarHeight = ref(system.getStatusBarHeight())
const subscribing = ref(false)
const selectedPlan = ref('monthly') // 默认选择月卡

// 用户信息
const userInfo = computed(() => {
  return userStore.userInfo || {}
})

// 微信绑定状态
const isWechatBound = computed(() => wechatStore.isBound)
const isCheckingBinding = computed(() => wechatStore.isCheckingBinding)
const isBinding = computed(() => wechatStore.isBinding)

// 选择套餐
const selectPlan = (plan) => {
  selectedPlan.value = plan
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 处理订阅 - 集成微信绑定逻辑
const handleSubscribe = async () => {
  try {
    if (subscribing.value) return
    subscribing.value = true
    
    // 获取用户ID
    const userId = uni.getStorageSync('userId')
    if (!userId) {
      message.error('用户未登录，请先登录')
      subscribing.value = false
      return
    }
    
    // 1. 首先检查用户是否已绑定微信
    console.log('【会员订阅】开始检查微信绑定状态')
    const isBound = await wechatStore.checkWechatBinding(userId)
    
    // 2. 如果未绑定微信，先进行微信授权绑定
    if (!isBound) {
      console.log('【会员订阅】用户未绑定微信，开始微信授权')
      const authResult = await wechatStore.authorizeAndBindWechat(userId)
      if (!authResult) {
        message.error('微信授权失败，无法进行支付')
        subscribing.value = false
        return
      }
      console.log('【会员订阅】微信授权绑定成功')
    } else {
      console.log('【会员订阅】用户已绑定微信，直接创建订单')
    }
    
    // 3. 微信绑定成功后，继续创建订单流程
    await createSubscriptionOrder()
    
  } catch (error) {
    console.error('【会员订阅】订阅处理异常:', error)
    message.error('订阅失败，请稍后重试')
  } finally {
    subscribing.value = false
  }
}

// 创建订阅订单 - 提取为独立函数
const createSubscriptionOrder = async () => {
  try {
    // 确定会员等级ID（使用普通会员ID=2）
    const levelId = 2
    
    // 确定订阅类型
    const subscriptionType = selectedPlan.value === 'monthly' ? 'MONTHLY' : 'YEARLY'
    
    // 确定金额 (分) - 月卡改为990分（9.9元）
    const amount = selectedPlan.value === 'monthly' ? 990 : 9900 
    
    // 获取客户端IP
    let clientIp = '127.0.0.1'
    try {
      clientIp = await getClientIp()
    } catch (error) {
      console.log('【会员订阅】获取客户端IP失败，使用默认IP:', error)
    }
    
    // 获取用户ID
    const userId = uni.getStorageSync('userId')
    
    // 创建参数对象
    const params = {
      userId: userId,
      levelId: levelId,
      subscriptionType: subscriptionType,
      amount: amount,
      clientIp: clientIp,
      payType: 'miniapp'
    }
    
    console.log('【会员订阅】订阅参数:', JSON.stringify(params))
    
    // 创建订阅订单
    const result = await membershipStore.createSubscriptionOrder(params)
    if (!result || !result.orderId) {
      message.error('创建订单失败，请重试')
      return
    }
    
    // 跳转到支付页面
    uni.navigateTo({
      url: `/pages/payment/index?orderId=${result.orderId}&type=vip&amount=${amount}`,
      success: () => {
        console.log('【会员订阅】成功跳转到支付页面')
      },
      fail: (err) => {
        message.error('跳转支付页面失败')
        console.log('【会员订阅】跳转支付页面失败:', err)
      }
    })
  } catch (error) {
    console.error('【会员订阅】创建订单异常:', error)
    message.error('创建订单失败，请重试')
  }
}

// 获取客户端IP地址
const getClientIp = () => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: getBaseUrl() + '/wechat/pay/client-ip',
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + uni.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          console.log('【会员订阅】获取客户端IP成功:', res.data.data)
          resolve(res.data.data || '127.0.0.1')
        } else {
          console.log('【会员订阅】获取客户端IP失败:', res.data)
          resolve('127.0.0.1')
        }
      },
      fail: (err) => {
        console.error('【会员订阅】获取客户端IP请求失败:', err)
        resolve('127.0.0.1')
      }
    })
  })
}

onMounted(async () => {
  // 页面加载时可以预先检查微信绑定状态
  const userId = uni.getStorageSync('userId')
  if (userId) {
    await wechatStore.checkWechatBinding(userId)
  }
})
</script>

<style lang="scss">
.membership-container {
  min-height: 100vh;
  background-color: #f1f5ff;
  padding-bottom: 30rpx;

  // 导航栏
  .nav-bar {
    height: 88rpx;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    background: #fff;
    position: relative;
    z-index: 100;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .back-button {
      position: absolute;
      left: 30rpx;
      z-index: 10;
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 30rpx;
      background: rgba(245, 245, 245, 0.5);
      transition: all 0.2s ease;

      .iconfont {
        font-size: 36rpx;
        color: #333;
        font-weight: 300;
      }

      &:active {
        background: rgba(230, 230, 230, 0.8);
        transform: scale(0.95);
      }
    }

    .title {
      width: 100%;
      text-align: center;
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      letter-spacing: 1rpx;
      position: relative;
    }
  }

  // VIP卡片
  .vip-card {
    margin: 20rpx 20rpx 30rpx;
    border-radius: 16rpx;
    background: #fff;
    padding: 30rpx;
    position: relative;
    overflow: hidden;
    box-shadow: 0 8rpx 20rpx rgba(255, 215, 0, 0.15); // 金色阴影

    .vip-header {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;

      .vip-icon {
        width: 60rpx;
        height: 60rpx;
        background: #FFD700; // 会员黄色
        color: #fff;
        font-size: 32rpx;
        font-weight: bold;
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16rpx;
        text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
      }

      .vip-title {
        flex: 1;
        display: flex;
        flex-direction: column;

        .main-title {
          font-size: 34rpx;
          color: #333;
          font-weight: 600;
          margin-bottom: 6rpx;
        }

        .sub-title {
          font-size: 24rpx;
          color: #666;
        }
      }

      .vip-badge {
        padding: 6rpx 16rpx;
        background: #FFD700; // 会员黄色
        color: #fff;
        font-size: 24rpx;
        border-radius: 20rpx;
        text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
      }
    }
  }

  // 套餐选择
  .plan-options {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;

    .plan-card {
      flex: 1;
      height: 160rpx;
      margin: 0 10rpx;
      background: #f8f8f8;
      border-radius: 16rpx;
      padding: 20rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      border: 2rpx solid transparent;
      transition: all 0.3s ease;

      &:first-child {
        margin-left: 0;
      }

      &:last-child {
        margin-right: 0;
      }

      &.active {
        border-color: #FFD700; // 会员黄色边框
        background: rgba(255, 215, 0, 0.08); // 淡金色背景
        box-shadow: 0 4rpx 12rpx rgba(255, 215, 0, 0.2);
      }

      .plan-price {
        display: flex;
        align-items: flex-end;

        .price-symbol {
          font-size: 28rpx;
          color: #333;
          margin-right: 4rpx;
          margin-bottom: 4rpx;
        }

        .price-value {
          font-size: 48rpx;
          color: #333;
          font-weight: 600;
          line-height: 1;
        }
      }

      .plan-details {
        display: flex;
        flex-direction: column;

        .plan-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 6rpx;
        }

        .plan-duration {
          font-size: 22rpx;
          color: #999;
        }
      }
    }
  }

  // 订阅按钮
  .subscribe-btn-container {
    margin-bottom: 16rpx;
  }

  .subscribe-btn {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%); // 金色渐变背景
    color: #fff;
    font-size: 30rpx;
    border-radius: 40rpx;
    text-align: center;
    box-shadow: 0 6rpx 12rpx rgba(255, 215, 0, 0.3); // 金色阴影
    transition: all 0.3s ease;
    text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);

    &:active {
      opacity: 0.9;
      transform: scale(0.98);
    }
  }

  .terms-text {
    text-align: center;
    font-size: 22rpx;
    color: #999;
    margin-top: 16rpx;
  }

  // 会员权益
  .benefits-section {
    margin: 0 20rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 20rpx;
      position: relative;
      padding-left: 20rpx;

      &:before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 32rpx;
        background: #FFD700; // 会员黄色装饰条
        border-radius: 3rpx;
      }
    }

    .benefits-list {
      background: #fff;
      border-radius: 16rpx;
      padding: 20rpx 30rpx;
      box-shadow: 0 4rpx 16rpx rgba(255, 215, 0, 0.08); // 淡金色阴影

      .benefit-item {
        display: flex;
        align-items: center;
        padding: 16rpx 0;
        border-bottom: 1rpx solid #f5f5f5;

        &:last-child {
          border-bottom: none;
        }

        .benefit-icon {
          width: 40rpx;
          font-size: 28rpx;
          color: #FFD700; // 会员黄色图标
          margin-right: 16rpx;
          font-weight: bold;
        }

        .benefit-text {
          font-size: 28rpx;
          color: #333;
        }
      }
    }
  }
}
</style>